package everyday;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/6/15 20:11
 * 202. 快乐数
 * https://leetcode.cn/problems/happy-number/
 */
public class Solution202 {

    // 快慢指针法判断快乐数
    public boolean isHappy(int n) {
        int slow = n, fast = bitSum(n);
        while (slow != fast) {
            slow = bitSum(slow);
            fast = bitSum(bitSum(fast));
        }
        return slow == 1;
    }

    // 返回 n 的每一位平方和
    private int bitSum(int n) {
        int res = 0;
        while (n > 0) {
            int t = n % 10;
            res += t * t;
            n /= 10;
        }
        return res;
    }
}
